package com.financing.wap.web.controller.api;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.ActivitiesGroupDTO;
import com.financing.wap.dto.FaUserWechatDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IActivitesGroupService;
import com.financing.wap.service.IUserService;
import com.financing.wap.service.IUserWechatService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.ActivitiesGroupVO;
import com.financing.wap.web.controller.BaseController;

/**
 * 组团1000活动
 * @author ios
 *
 */
@Controller("activitiesGroupController")
@RequestMapping("/api/activitiesGroup")
public class ActivitiesGroupController extends BaseController {
	
	@Autowired
	private IActivitesGroupService activitiesGroupService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IUserWechatService userWechatServiceImpl;
	

	/**
	 * 加入团队
	 * @param request
	 * @param response
	 * @param agd
	 * @return
	 */
	@RequestMapping("/joinGroup")
	@ResponseBody
	public ResultMap joinGroup(HttpServletRequest request, HttpServletResponse response,ActivitiesGroupDTO agd){
		ResultMap result = new ResultMap();
		try{
			
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			loginUser = userService.queryUserById(loginUser.getId());
			//团ID不允许为空
			if(StringUtil.isNullOrEmptyStr(agd.getFpGroupId())){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			
			//认证通过的用户不允许加团
			if(!("1".equals(loginUser.getRole()) || "98".equals(loginUser.getRole()) ||"99".equals(loginUser.getRole()))){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_GROUP_HAD_AUTHENTICATION);
				return result;
			}
			
			ActivitiesGroupDTO param = new ActivitiesGroupDTO();
			param.setFpGroupId(agd.getFpGroupId());
			DTOdateSetUtil.setCreateInfo(param);
			DTOdateSetUtil.setUpdateInfo(param);
			param.setFpFaId(loginUser.getId());
			
			String resultStr =  activitiesGroupService.addActivitiesGroupMember(param);
			
			if(ResultMap.STATUS_CODE_SUCCESS.equals(resultStr)){
				result.setStatus(STATUS.SUCCESS);
			}else{
				result.setStatus(STATUS.ERROR);
			}
			result.setStatusCode(resultStr);
			return result;
		}catch(Exception e){
			log.error("join group error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
	}

	/**
	 * 创建团队
	 * @param request
	 * @param response
	 * @param agd
	 * @return
	 */
	@RequestMapping("/addGroup")
	@ResponseBody
	public ResultMap addGroup(HttpServletRequest request, HttpServletResponse response,ActivitiesGroupDTO agd){
		ResultMap result = new ResultMap();
		try{
			
			//团名称和团总人数不能为空
			if(StringUtil.isNullOrEmptyStr(agd.getFpGroupName()) || agd.getFpGroupTotalMember() == null){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			loginUser = userService.queryUserById(loginUser.getId());
			
			ActivitiesGroupDTO param = new ActivitiesGroupDTO();
			param.setFpGroupId(agd.getFpGroupId());
			DTOdateSetUtil.setCreateInfo(param);
			DTOdateSetUtil.setUpdateInfo(param);
			param.setFpFaId(loginUser.getId());
			param.setFpGroupHeadId(loginUser.getId());
			param.setFpGroupName(agd.getFpGroupName());
			param.setFpGroupCreateTime(new Date());
			param.setFpGroupTotalMember(agd.getFpGroupTotalMember());
			
			//3个人团200奖金 5个人团400奖金  10个人团1000奖金 其他人数直接报错
			//活动重新开始-金额变动 20161219
			//3个人团88奖金 5个人团188奖金  10个人团500奖金 其他人数直接报错
			int totalMember = agd.getFpGroupTotalMember();
			if(totalMember == 3){
				param.setFpGroupTotalAmount(new BigDecimal(88));
			}else if(totalMember == 5){
				param.setFpGroupTotalAmount(new BigDecimal(188));
			}else if(totalMember == 10){
				param.setFpGroupTotalAmount(new BigDecimal(500));
			}else{
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_GROUP_TOTAL_MEMBER_ERROR);
				return result;
			}
			param.setFpGroupStatus(Constants.ActivitiesGroupDTO.STATUS_CREATE);
			param.setFpGroupSendAmount(new BigDecimal(0));
			
			String resultStr =  activitiesGroupService.createActivitesGroup(param);
			
			result.setAttribute("activitiesGroupInfo", param);
			
			if(ResultMap.STATUS_CODE_SUCCESS.equals(resultStr)){
				result.setStatus(STATUS.SUCCESS);
			}else{
				result.setStatus(STATUS.ERROR);
			}
			
			result.setStatusCode(resultStr);
			return result;
		}catch(Exception e){
			log.error("create group error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
	}
	
	/**
	 * 查询自己团队列表
	 * @param request
	 * @param response
	 * @param agd
	 * @return
	 */
	@RequestMapping("/listGroups")
	@ResponseBody
	public ResultMap listGroups(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		try{
			
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			loginUser = userService.queryUserById(loginUser.getId());
			
			ActivitiesGroupDTO param = new ActivitiesGroupDTO();
			param.setFpFaId(loginUser.getId());
			
			List<ActivitiesGroupDTO> listResult = activitiesGroupService.queryFaOwnGroup(param);
			
			ActivitiesGroupDTO runActivitiesGroup  = null;
			ActivitiesGroupDTO lastSuccessGroup = new ActivitiesGroupDTO();
			
			//取在进行中的团或者最后创建的团
			for(ActivitiesGroupDTO tmp : listResult){
				if("1".equals(tmp.getFpGroupStatus())){
					runActivitiesGroup = tmp;
					break;
				}
				if(null == lastSuccessGroup.getFpGroupCreateTime() || lastSuccessGroup.getFpGroupCreateTime().before(tmp.getFpGroupCreateTime())){
					lastSuccessGroup = tmp;
				}
			}
			
			if(null != runActivitiesGroup && runActivitiesGroup.getFpGroupStatus() != null){
				result.setAttribute("run", runActivitiesGroup);
			} else if(null != lastSuccessGroup && lastSuccessGroup.getFpGroupCreateTime()!=null){
				result.setAttribute("run", lastSuccessGroup);
			}else{
				result.setAttribute("run", null);
			}
			
			result.setAttribute("list", listResult);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(STATUS.SUCCESS);
			return result;
		}catch(Exception e){
			log.error("create group error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
	}
	

	/**
	 * 查询分享页面团信息
	 * @param request
	 * @param response
	 * @param agd
	 * @return
	 */
	@RequestMapping("/shareGroupInfo")
	@ResponseBody
	public ResultMap shareGroupInfo(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		try{
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			//loginUser = userService.queryUserById(loginUser.getId());
			
			ActivitiesGroupDTO agd = new ActivitiesGroupDTO();
			agd.setFpGroupId(request.getParameter("fpGroupId"));
			//判断参数团Id是否传入
			if(StringUtil.isNullOrEmptyStr(agd.getFpGroupId())){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			
			//判断团是否存在
			ActivitiesGroupVO agv = activitiesGroupService.queryShareActivitiesGroup(agd);
			if(null == agv){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_GROUP_NOT_EXIS);
				return result;
			}
			
			//返回团信息
			agv.setFpGroupCreateTime(DateUtil.addHour(agv.getFpGroupCreateTime(),48));
			
			List<ActivitiesGroupVO> listAll = activitiesGroupService.queryActivitiesGroupMemberInfo(agd);
			
			//验证通过列表
			List<ActivitiesGroupVO> listHasRole = new ArrayList<ActivitiesGroupVO>();
			
			//验证未通过列表
			List<ActivitiesGroupVO> listNoRole = new ArrayList<ActivitiesGroupVO>();
			
			result.setAttribute("canOPen", false);
			
			for(ActivitiesGroupVO temp : listAll){
				temp.setMobile(StringUtil.mobileHide4Number(temp.getMobile()));
				if(temp.getHeadWechatName()!=null && temp.getHeadWechatName().length()>6){
					temp.setHeadWechatName(temp.getHeadWechatName().substring(0, 6)+"*");
				}
				if("1".equals(temp.getRole()) || "98".equals(temp.getRole())|| "99".equals(temp.getRole())){
					listNoRole.add(temp);
				}else{
					listHasRole.add(temp);
					
					if(loginUser != null){
						if(temp.getFpFaId().equals(loginUser.getId()) && "1".equals(temp.getFpGroupSendAmountStatus())){
							result.setAttribute("canOPen", true);
						}
					}
					
				}
			}
			
			
			agv.setSpeed(listHasRole.size()*100/agv.getFpGroupTotalMember());
			result.setAttribute("groupInfo", agv);
			//result.setAttribute("noRoleList", listNoRole);
			result.setAttribute("noRoleList", listNoRole);
			result.setAttribute("hasRoleList", listHasRole);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(STATUS.SUCCESS);
			return result;
		}catch(Exception e){
			log.error("create group error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
	}
	
	/**
	 * 查询红包列表
	 * @param request
	 * @param response
	 * @param agd
	 * @return
	 */
	@RequestMapping("/listOwnGift")
	@ResponseBody
	public ResultMap listOwnGift(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		try{
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			loginUser = userService.queryUserById(loginUser.getId());
			
			//获取参数团ID
			String fpGroupId = request.getParameter("fpGroupId");
			
			ActivitiesGroupDTO agd = new ActivitiesGroupDTO();
			
			//未获取到团ID 则查询自己领取金额的明细 否则查询组金额领取的明细
			if(!StringUtil.isNullOrEmptyStr(fpGroupId)){
				agd.setFpGroupId(fpGroupId);
				agd.setFpFaId(loginUser.getId());
			}else{
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			
			List<ActivitiesGroupDTO> list = activitiesGroupService.queryFaOwnGroup(agd);
		   if(null!= list && list.size()==1){
			   if("2".equals(list.get(0).getFpGroupSendAmountStatus())){
				   result.setAttribute("isOpen", true);
			   }else if("1".equals(list.get(0).getFpGroupSendAmountStatus())){
				   request.setAttribute("isOpen", false);
			   }else{
				   result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_GROUP_NO_RED);
					return result;
			   }
		   }
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(STATUS.SUCCESS);
			return result;
		}catch(Exception e){
			log.error("create group error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
	}
	
	/**
	 * 查询红包列表
	 * @param request
	 * @param response
	 * @param agd
	 * @return
	 */
	@RequestMapping("/listGift")
	@ResponseBody
	public ResultMap listGift(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		try{
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			loginUser = userService.queryUserById(loginUser.getId());
			
			//获取参数团ID
			String fpGroupId = request.getParameter("fpGroupId");
			
			ActivitiesGroupDTO agd = new ActivitiesGroupDTO();
			
			//未获取到团ID 则查询自己领取金额的明细 否则查询组金额领取的明细
			if(!StringUtil.isNullOrEmptyStr(fpGroupId)){
				agd.setFpGroupId(fpGroupId);
			}else{
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			
			agd.setFpGroupSendAmountStatus("2");
			List<ActivitiesGroupVO> res = activitiesGroupService.queryActivitiesGroupSendAmount(agd);
			
			ActivitiesGroupVO self = null;
			
			//给出最佳获得者
			if(!res.isEmpty() && !StringUtil.isNullOrEmptyStr(fpGroupId)){
				ActivitiesGroupVO bestGift = res.get(0);
				for(ActivitiesGroupVO agvo : res){
					if(!StringUtil.isNullOrEmptyStr(fpGroupId)){
						if(agvo.getFpFaId().equals(loginUser.getId())){
							self = agvo;
						}
					}
					if(bestGift.getaAmount().compareTo(agvo.getaAmount()) < 0){
						bestGift = agvo;
					}else{
						agvo.setIsBestGift(false);
					}
				}
				
				if(res.size() >= res.get(0).getFpGroupTotalMember()){
					bestGift.setIsBestGift(true);
				}
			}
			
			if(!StringUtil.isNullOrEmptyStr(fpGroupId)){
				if(self == null){
					self = new ActivitiesGroupVO();
				}
				result.setAttribute("activitiesGroupGift", self);
				//查询未提现红包信息
				agd.setFpFaId(loginUser.getId());
				BigDecimal totalAmount = activitiesGroupService.queryOneUserNotGetGiftAmount(agd);
				if(totalAmount == null){
					totalAmount = new BigDecimal(0);
				}
				result.setAttribute("totalGetAmount", totalAmount);
			}
			
			//查询自己的图像和当前团的红包
			ActivitiesGroupDTO agdOwn = new ActivitiesGroupDTO();
			agdOwn.setFpFaId(loginUser.getId());
			agdOwn.setFpGroupId(fpGroupId);
			
			BigDecimal totalGetAmount = activitiesGroupService.getGroupAmount(agdOwn);
			
			FaUserWechatDTO faUserWechatDTO = new FaUserWechatDTO();
			faUserWechatDTO.setUserId(loginUser.getId());
			faUserWechatDTO = userWechatServiceImpl.queryUserWechatInfo(faUserWechatDTO);
			String imagUrl = faUserWechatDTO.getHeadimgurl();
			
			result.setAttribute("imagUrl", imagUrl);
			result.setAttribute("totalAmount", totalGetAmount);
			result.setAttribute("list", res );
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(STATUS.SUCCESS);
			return result;
		}catch(Exception e){
			log.error("create group error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
	}
	
	/**
	 * 拆红包
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/openGift")
	@ResponseBody
	public ResultMap openGift(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		try{
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			loginUser = userService.queryUserById(loginUser.getId());
			
			String uRole = loginUser.getRole();
			
			System.out.println("uRole is :"+uRole);
			if("1".equals(uRole) || "98".equals(uRole) || "99".equals(uRole)){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_AUTHENTICATION_ERROE);
				return result;
			}
			
			//获取参数团ID
			String fpGroupId = request.getParameter("fpGroupId");
			if(StringUtil.isNullOrEmptyStr(fpGroupId)){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			
			ActivitiesGroupDTO agd = new ActivitiesGroupDTO();
			
			agd.setFpFaId(loginUser.getId());
			agd.setFpGroupId(fpGroupId);
			
			//拆红包
			String resultStr = activitiesGroupService.openGift(agd);
			if(ResultMap.STATUS_CODE_SUCCESS.equals(result) || ResultMap.STATUS_CODE_ACTIVITIES_GROUP_RED_ERROR.equals(result)){
				result.setStatus(STATUS.SUCCESS);
			}else{
				result.setStatus(STATUS.FAILE);
			}
			result.setStatusCode(resultStr);
			return result;
		}catch(Exception e){
			log.error("create group error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
	}
	
	/**
	 * 修改团名称
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/changeGroupName")
	@ResponseBody
	public ResultMap changeGroupName(HttpServletRequest request, HttpServletResponse response,ActivitiesGroupDTO agd){
		ResultMap result = new ResultMap();
		try{
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			
			if(StringUtil.isNullOrEmptyStr(agd.getFpGroupName()) || StringUtil.isNullOrEmptyStr(agd.getFpGroupId())){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			
			agd.setFpFaId(loginUser.getId());
			
			activitiesGroupService.updateActivitiesGroupName(agd);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(STATUS.SUCCESS);
			return result;
		}catch(Exception e){
			log.error("change group name error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
	}
}
